//
//  CodeBarViewController.m
//  CheZhu-Merchant
//
//  Created by Calvin on 14/11/26.
//  Copyright (c) 2014年 智道安盈. All rights reserved.
//

#import "CodeBarViewController.h"
#import "LBXScanResult.h"
#import "LBXScanWrapper.h"
#import "Record.h"
@implementation CodeBarViewController


- (void)viewDidLoad {

    [super viewDidLoad];
    
    [self setNaviBarTitle: @"二维码扫描"];

    // 创建一个自定义的按钮，并添加到导航条左侧。
    UIButton *btnNaviLeft = [CustomNaviBarView createImgNaviBarBtnByImgNormal:@"bar_left_image"
                                                                 imgHighlight:@"bar_left_image_f"
                                                                       target:self
                                                                       action:@selector(btnNaviLeftClick)];
    [self setNaviBarLeftBtn:btnNaviLeft];
    
    //设置扫码后需要扫码图像
    self.isNeedScanImage = YES;
    tapView = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [tapView setTitle:@"轻触继续扫描" forState:UIControlStateNormal];
    [tapView setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [tapView setBackgroundColor:[UIColor colorWithWhite:1 alpha:0.6]];
    tapView.titleLabel.font = [UIFont systemFontOfSize:15];
    [tapView addTarget:self action:@selector(reStartDevice) forControlEvents:UIControlEventTouchUpInside];
    localRecordArr = [Record findWithFormat:@"WHERE %@ = %d ",@"type", self.type];

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [self drawScanView];
    [self performSelector:@selector(startScan) withObject:nil afterDelay:0.2];
    if (_isQQSimulator) {
        [self drawTitle];
        
        // 创建一个自定义的按钮，并添加到导航条右侧。
        UIButton*_btnNaviRight = [CustomNaviBarView
                                  createNormalNaviBarBtnByTitle:@"开始纪录"
                                  target:self
                                  action:@selector(btnNaviRightClick)];
        [self setNaviBarRightBtn:_btnNaviRight];
        
        UIFont *inputFont = [UIFont flatFontOfSize:g_fSize_AppFont];
        UILabel *codeTitleLabel = [[UILabel alloc] initWithFrame:
                                   CGRectMake(0, 0, 80, 50)];
        codeTitleLabel.backgroundColor = [UIColor clearColor];
        codeTitleLabel.font = inputFont;
        codeTitleLabel.textAlignment = 1;
        codeTitleLabel.textColor = [UIColor whiteColor];
        codeTitleLabel.text = @"记录号:";
        
        UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
        [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
        [saveBtn addTarget:self action:@selector(saveAction) forControlEvents:UIControlEventTouchUpInside];
        saveBtn.titleLabel.font = inputFont;
        [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        //扫码区域Y轴最小坐标
        CGRect frame = self.view.frame;
        
        int XRetangleLeft = self.style.xScanRetangleOffset;
        
        CGSize sizeRetangle = CGSizeMake(frame.size.width - XRetangleLeft*2, frame.size.width - XRetangleLeft*2);
        CGFloat YMinRetangle = frame.size.height / 2.0 - sizeRetangle.height/2.0 - self.style.centerUpOffset;
        CGFloat YMaxRetangle = YMinRetangle + sizeRetangle.height;
        _codeTextField = [[UITextField alloc] initWithFrame:
                          CGRectMake((self.view.frame.size.width - 300)/2, YMaxRetangle + 10 + fHeight_StatueBar + fHeight_Nav, 300, 50)];
        _codeTextField.delegate = self;
        _codeTextField.backgroundColor = [UIColor clearColor];
        _codeTextField.font = inputFont;
        _codeTextField.textColor = [UIColor whiteColor];
        _codeTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _codeTextField.returnKeyType = UIReturnKeyNext;
        _codeTextField.keyboardType = UIKeyboardTypeDefault;
        _codeTextField.leftViewMode = UITextFieldViewModeAlways;
        _codeTextField.rightViewMode = UITextFieldViewModeAlways;
        _codeTextField.rightView = saveBtn;
        _codeTextField.leftView = codeTitleLabel;
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"扫描或输入"];
        [string addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithWhite:0.6 alpha:1] range:NSMakeRange(0, string.length)];
        _codeTextField.attributedPlaceholder = string;
        _codeTextField.userInteractionEnabled = YES;
        [self.view addSubview:_codeTextField];
        
        [self.view bringSubviewToFront:_topTitle];
        [self.view bringSubviewToFront:_codeTextField];
        tableView = [[UITableView alloc] initWithFrame:CGRectMake(_codeTextField.left, _codeTextField.bottom+10, _codeTextField.width, ScreenHeight-_codeTextField.bottom-10) style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        [self.view addSubview:tableView];
        tableView.backgroundColor = [UIColor clearColor];
        [self setExtraCellLineHidden:tableView];
        
    }
    else
        _topTitle.hidden = YES;
}
-(void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [_scanObj stopScan];
    [_qRScanView stopScanAnimation];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)saveAction
{
    if (_codeTextField.text.length == 0) {
        return;
    }
    if ([self record:_codeTextField.text]) {
        _codeTextField.text = nil;
    }
}

#pragma mark - UserAction
-(void)btnNaviLeftClick
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)btnNaviRightClick
{
    if(recordArray.count == 0)
    {
        [self.view makeToast:@"记录号不能为空"];
        return;
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(didSaoMiaoFinished:withCodeArr:)])
    {
        [self.delegate didSaoMiaoFinished:self withCodeArr:recordArray];
    }
    [self btnNaviLeftClick];
}



//绘制扫描区域
- (void)drawScanView
{
    if (!_qRScanView)
    {
        CGRect rect = self.view.frame;
        rect.origin = CGPointMake(0, fHeight_StatueBar + fHeight_Nav);
        rect.size.height = rect.size.height - rect.origin.y;
        self.qRScanView = [[LBXScanView alloc] initWithFrame:rect style:_style];
        [self.view addSubview:_qRScanView];
        CGFloat retangle = self.qRScanView.frame.size.width - self.style.xScanRetangleOffset*2;
        CGFloat YMinRetangle = self.qRScanView.frame.size.height / 2.0 - retangle/2.0 - self.style.centerUpOffset;
        tapView.frame = CGRectMake(self.style.xScanRetangleOffset, YMinRetangle, ScreenWidth-self.style.xScanRetangleOffset*2, ScreenWidth-self.style.xScanRetangleOffset*2);
        [self.qRScanView addSubview:tapView];
        tapView.hidden = YES;
    }
    
    [_qRScanView startDeviceReadyingWithText:@"相机启动中"];
}

- (void)reStartDevice
{
    tapView.hidden = YES;
    [_scanObj startScan];
    [_qRScanView startScanAnimation];

}

-(void)stopScan
{
    [_scanObj stopScan];
    [_qRScanView stopScanAnimation];
}
//启动设备
- (void)startScan
{
    tapView.hidden = YES;
    if ( ![LBXScanWrapper isGetCameraPermission] )
    {
        [_qRScanView stopDeviceReadying];
        [self.view hideToastActivityWithError:@"   请到设置隐私中开启本程序相机权限   " completion:nil];
        return;
    }
    if (!_scanObj )
    {
        __weak __typeof(self) weakSelf = self;
        // AVMetadataObjectTypeQRCode   AVMetadataObjectTypeEAN13Code
        
        CGRect cropRect = CGRectZero;
        if (_isOpenInterestRect) {
            
            cropRect = [LBXScanView getScanRectWithPreView:self.view style:_style];
        }
        
        UIView *videoView = [[UIView alloc] initWithFrame:
                             CGRectMake(0, fHeight_StatueBar + fHeight_Nav,
                                        CGRectGetWidth(self.view.frame),
                                        CGRectGetHeight(self.view.frame) - fHeight_StatueBar - fHeight_Nav)];
        videoView.backgroundColor = [UIColor redColor];
        [self.view insertSubview:videoView atIndex:0];
        
        self.scanObj = [[LBXScanWrapper alloc]initWithPreView:videoView
                                              ArrayObjectType:nil
                                                     cropRect:cropRect
                                                      success:^(NSArray<LBXScanResult *> *array){
                                                          [weakSelf scanResultWithArray:array];
                                                      }];
        
        [_scanObj setNeedCaptureImage:_isNeedScanImage];
        
        [self cameraInitOver];
    }
    [_scanObj startScan];
    [_qRScanView stopDeviceReadying];
    [_qRScanView startScanAnimation];
}

- (void)cameraInitOver
{
    if (self.isVideoZoom)
    {
        [self zoomView];
    }
}

//绘制扫描区域
- (void)drawTitle
{
    if (!_topTitle)
    {
        self.topTitle = [[UILabel alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 145)/2,
                                                                  fHeight_StatueBar + fHeight_Nav + 0, 145, 60)];
        _topTitle.textAlignment = NSTextAlignmentCenter;
        _topTitle.numberOfLines = 0;
        _topTitle.text = @"将取景框对准二维码即可自动扫描";
        _topTitle.textColor = [UIColor whiteColor];
        [self.view addSubview:_topTitle];
    }
}

- (LBXScanVideoZoomView*)zoomView
{
    if (!_zoomView)
    {
        
        CGRect frame = self.view.frame;
        
        int XRetangleLeft = self.style.xScanRetangleOffset;
        
        CGSize sizeRetangle = CGSizeMake(frame.size.width - XRetangleLeft*2, frame.size.width - XRetangleLeft*2);
        
        if (self.style.whRatio != 1)
        {
            CGFloat w = sizeRetangle.width;
            CGFloat h = w / self.style.whRatio;
            
            NSInteger hInt = (NSInteger)h;
            h  = hInt;
            
            sizeRetangle = CGSizeMake(w, h);
        }
        
        CGFloat videoMaxScale = [self.scanObj getVideoMaxScale];
        
        //扫码区域Y轴最小坐标
        CGFloat YMinRetangle = frame.size.height / 2.0 - sizeRetangle.height/2.0 - self.style.centerUpOffset;
        CGFloat YMaxRetangle = YMinRetangle + sizeRetangle.height;
        
        CGFloat zoomw = sizeRetangle.width + 20;
        _zoomView = [[LBXScanVideoZoomView alloc] initWithFrame:
                     CGRectMake((CGRectGetWidth(self.view.frame) - zoomw)/2,
                                YMaxRetangle + 0 + fHeight_StatueBar + fHeight_Nav,
                                zoomw, 18)];
        _zoomView.hidden = NO;
        [_zoomView setMaximunValue:videoMaxScale/4];
        
        [_zoomView setSliderValue:4.0f];
        [self.scanObj setVideoScale:4.0f];

        __weak __typeof(self) weakSelf = self;
        _zoomView.block= ^(float value)
        {
            [weakSelf.view hideToastActivityWithSuccess:[NSString stringWithFormat:@"当前焦距为：%.1f",value] completion:nil];
            [weakSelf.scanObj setVideoScale:value];
        };
        [self.view addSubview:_zoomView];
    }
    
    return _zoomView;
}

- (void)scanResultWithArray:(NSArray<LBXScanResult*>*)array
{
    if (array.count < 1)
    {
        NSLog(@"识别失败");
        return;
    }
    
    //经测试，可以同时识别2个二维码，不能同时识别二维码和条形码
    for (LBXScanResult *result in array)
    {
        NSLog(@"scanResult:%@",result.strScanned);
    }
    
    LBXScanResult *scanResult = array[0];
    NSString*strResult = scanResult.strScanned;
    self.scanImage = scanResult.imgScanned;
    if (!strResult)
    {
        NSLog(@"识别失败");
        return;
    }
    
    [self showNextVCWithScanResult:scanResult];
}

- (void)showNextVCWithScanResult:(LBXScanResult*)strResult
{
    [self reStartDevice];
    NSLog(@"类别:%@, 扫码内容:%@",strResult.strBarCodeType, strResult.strScanned);
    _codeTextField.text = strResult.strScanned;
    [self record:strResult.strScanned];
}

-(BOOL)record:(NSString *)string
{
    tapView.hidden = NO;
    [self stopScan];
    NSArray *onlineArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"onlineData"];
    if ([onlineArray isKindOfClass:[NSDictionary class]]) {
        onlineArray = [NSMutableArray arrayWithCapacity:0];
    }
    for (NSArray *tmpArr in onlineArray) {
        if (tmpArr.count>2&&self.type==[tmpArr[1] integerValue]&&[tmpArr[2] isEqualToString:string]) {
            [self.view makeToast:@"服务器已存在相同样本"];
            return NO;
        }
    }
    if (recordArray.count == 0) {
        recordArray = [NSMutableArray arrayWithCapacity:0];
    }
    for (Record *mode in localRecordArr) {
        if ([mode.recordId isEqualToString:string]) {
            [self.view makeToast:@"之前已保存相同样本"];
            return NO;
        }
    }
    
    for (NSString *tmpstring in recordArray) {
        if ([string isEqualToString:tmpstring]) {
            [self.view makeToast:@"刚才已添加相同样本"];
            return NO;
        }
    }
    [recordArray addObject:string];
    
    [tableView reloadData];
    return YES;
}

#pragma mark - UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return recordArray.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 30;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecordTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[RecordTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
       cell.deleteBtn = [[UIButton alloc] initWithFrame:CGRectMake(tableView.width-30, 5, 20, 20)];
        [cell.deleteBtn setBackgroundImage:[UIImage imageNamed:@"deleteRecord"] forState:UIControlStateNormal];
        [cell.deleteBtn addTarget:self action:@selector(deleteAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:cell.deleteBtn];
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.backgroundColor = [UIColor clearColor];
    }
    cell.deleteBtn.tag = indexPath.row+1;
    cell.textLabel.text = [recordArray objectAtIndex:indexPath.row];
    cell.textLabel.textColor = [UIColor colorWithWhite:0.6 alpha:1];
    return cell;
}

-(void)deleteAction:(UIButton *)sender
{
    [recordArray removeObjectAtIndex:sender.tag-1];
    [tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:sender.tag-1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    [tableView reloadData];
}

#pragma mark - UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    
    return YES;
}

@end
@implementation RecordTableViewCell



@end
